# coding=utf-8

from app import db
from werkzeug.security import generate_password_hash, check_password_hash


class User(db.Model):
    __tablename__ = 'user'
    id = db.Column(db.Integer, primary_key=True, autoincrement=True)
    username = db.Column(db.String(60), nullable=False)
    password = db.Column(db.String(100), nullable=False)
    telephone = db.Column(db.String(11), nullable=False)
    create_time = db.Column(db.DateTime)

    def __init__(self, username, password, telephone, create_time):
        self.username = username
        self.password = generate_password_hash(password)
        self.telephone = telephone
        self.create_time = create_time

    def __repr__(self):
        return '<User --%r>' % self.username

    def check_password(self, source_password):
        print(self.password)
        return check_password_hash(self.password, source_password)


class Question(db.Model):
    __tablename = 'question'
    id = db.Column(db.Integer, primary_key=True, autoincrement=True)
    title = db.Column(db.String(50), nullable=False)
    content = db.Column(db.Text)
    create_time = db.Column(db.DateTime)
    user_id = db.Column(db.Integer, db.ForeignKey('user.id'))
    user = db.relationship('User', backref='questions', lazy=True)
    answers = db.relationship('Answer', backref='question', lazy=True)

    def __repr__(self):
        return '<Question --%r>' % self.title


class Answer(db.Model):
    __tablename__ = 'answer'
    id = db.Column(db.Integer, primary_key=True, autoincrement=True)
    content = db.Column(db.Text)
    create_time = db.Column(db.DateTime)
    question_id = db.Column(db.Integer, db.ForeignKey('question.id'))
    user_id = db.Column(db.Integer, db.ForeignKey('user.id'))
    author = db.relationship('User', backref='answer', lazy=True)

    def __repr__(self):
        return '<Answer--%r>' % self.content
